import config
import logging
import token_manage
# import timed_task
import timed_task_pro
import apscheduler.events
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.schedulers.background import BackgroundScheduler


_job_stores = {
    "default": RedisJobStore(db=config.REDIS_DB, host=config.REDIS_HOST,
                             port=config.REDIS_PORT,
                             password=config.REDIS_PASSWORD)
}
_executors = {
    "default": ThreadPoolExecutor(10)
}
_job_defaults = {
    "coalesce": True,
    "max_instance": 1,
    "misfire_grace_time": 5,
    "replace_existing": True
}

scheduler = BackgroundScheduler(jobstores=_job_stores, executors=_executors,
                                job_defaults=_job_defaults, timezone="Asia/Shanghai")


def scheduler_start_listener(event):
    _logger = logging.getLogger('Scheduler')
    _logger.info("Job Scheduler started.")


def scheduler_error_listener(event):
    global scheduler
    _logger = logging.getLogger('Scheduler')
    if event.exception and hasattr(event, "job_id"):
        _logger.exception(f"{str(event.job_id)} engage error, reschedule...")
        scheduler.reschedule_job(event.job_id)
    else:
        _logger.info(f"{str(event.job_id)} missed, reschedule...")
        scheduler.reschedule_job(event.job_id)


scheduler.add_listener(scheduler_start_listener, apscheduler.events.EVENT_SCHEDULER_START)
scheduler.add_listener(scheduler_error_listener, apscheduler.events.EVENT_JOB_ERROR |
                       apscheduler.events.EVENT_JOB_MISSED)

scheduler.add_job(token_manage.refresh_enterprise_app_token, "cron",
                  id="REF_ENT_APP_TOKEN", minute="*/5", replace_existing=True)
scheduler.add_job(token_manage.refresh_enterprise_app_js_api_ticket,
                  "cron", id="REF_ENT_JS_TICKET", minute="*/5", replace_existing=True)
scheduler.add_job(token_manage.refresh_public_app_token, "cron",
                  id="REF_PUB_APP_TOKEN", minute="*/5", replace_existing=True)
scheduler.add_job(token_manage.refresh_public_app_js_api_ticket, "cron",
                  id="REF_PUB_JS_TICKET", minute="*/5", replace_existing=True)
# scheduler.add_job(token_manage.web_tokens_surveillance, "cron",
#                   id="SURV_WEB_TICKETS", second="*/30", replace_existing=True)

# scheduler.add_job(timed_task.StaticsReport, "cron", id="TIMED_REPORT", hour="*/2", replace_existing=True)
scheduler.add_job(timed_task_pro.StatisticsBureauMonthlyReport, "cron",
                  id="TIMED_STAT_BMR", hour="22", replace_existing=True)
scheduler.add_job(timed_task_pro.StatisticsBureauWeeklyReport, "cron",
                  id="TIMED_STAT_BWR", hour="22", replace_existing=True)
scheduler.add_job(timed_task_pro.StatisticsUnresolvedIssueDetail, "cron",
                  id="TIMED_STAT_UID", hour="22", replace_existing=True)
scheduler.add_job(timed_task_pro.StatisticsUnresolvedIssueReport, "cron",
                  id="TIMED_STAT_UIR", hour="22", replace_existing=True)
scheduler.add_job(timed_task_pro.StatisticsUnresolvedIssueUrgeByStation, "cron",
                  id="TIMED_STAT_UIUS", hour="22", replace_existing=True)
scheduler.add_job(timed_task_pro.StatisticsUnresolvedIssueByType, "cron",
                  id="TIMED_STAT_UIT", hour="22", replace_existing=True)
scheduler.add_job(timed_task_pro.StatisticsVendorIssues, "cron",
                  id="TIMED_STAT_VI", hour="22", replace_existing=True)
